'use strict';

const { spawn } = require('child_process');

function isObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
}

function spinnerStart(msg = 'loading', spinnerString = '|/-\\') {
  const Spinner = require('cli-spinner').Spinner;
  const spinner = new Spinner(msg + ' %s');
  spinner.setSpinnerString(spinnerString);
  spinner.start();
  return spinner;
}

function sleep(timeout = 1000) {
  return new Promise(resolve => setTimeout(resolve, timeout));
}

function smartSpawn(...args) {
  const win32 = process.platform === 'win32';
  const [command, argv, options] = args;
  const cmd = win32 ? 'cmd' : command;
  const cmdArgs = win32 ? ['/c'].concat(command, argv) : argv;
  return spawn(cmd, cmdArgs, options || {});
}

function smartSpawnSync(...args) {
  return new Promise((resolve, reject) => {
    const childProcess = smartSpawn(...args);
    childProcess.on('error', error => {
      reject(error);
    });

    // 不能退出进程, 不然就相当于ctrl c 了
    childProcess.on('exit', code => {
      resolve(code);
    });
  });
}

const LOWEST_NODE_VERSION = '12.0.0';
const DEFAULT_CLI_HOME = '.ysx-cli';


module.exports = { isObject, spinnerStart, sleep, smartSpawn, smartSpawnSync, LOWEST_NODE_VERSION, DEFAULT_CLI_HOME };
